<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="测评问题id" prop="questionId">
        <el-input
          v-model="queryParams.questionId"
          placeholder="请输入测评问题id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="评量表" prop="scaleId">
        <el-input
          v-model="queryParams.scaleId"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       -->
      <!-- *****下拉框要scaleTitle -->
      <el-form-item label="评量表:" prop="scaleTitle">
        <!-- <el-input
          v-model="queryParams.scaleTitle"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-select v-model="queryParams.scaleTitle" @change="handleScaleId" clearable>
          <el-option v-for="(item,index) in scaleTitleList" :label="item.scaleTitle" :value="item.scaleTitle"
            :key="index" @keyup.enter.native="handleQuery"></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="问题序号" prop="questionOrder">
        <el-input
          v-model="queryParams.questionOrder"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="问题内容:" prop="questionContent" label-width="6rem">
        <el-input v-model="queryParams.questionContent" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="所属因子维度id" prop="factorId">
        <el-input
          v-model="queryParams.factorId"
          placeholder="请输入所属因子维度id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="因子维度:" prop="factorName" label-width="6rem">
        <!-- <el-input
          v-model="queryParams.factorName"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-select v-model="queryParams.factorName" @keyup.enter.native="handleQuery" placeholder="请选择" clearable>
          <el-option v-for="(item,index) in factorNameList" :label="item.factorName" :value="item.factorName"
            :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:questionTree:add']">添加</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:questionTree:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:questionTree:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:questionTree:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="questionTreeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="问题序号" align="center" prop="questionId" />
      <!-- <el-table-column label="所属测评量表id" align="center" prop="scaleId" /> -->
      <!-- <el-table-column label="问题序号" align="center" prop="questionOrder" /> -->
      <el-table-column label="问题内容" align="center" prop="questionContent" />
      <!-- <el-table-column label="所属因子维度id" align="center" prop="factorId" /> -->
      <el-table-column label="所属因子维度" align="center" prop="factorName" />
      <el-table-column label="所属测评量表" align="center" prop="scaleTitle" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:questionTree:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-list" @click="gotoOption(scope.row)">选项列表</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:questionTree:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination v-show="total > 0" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :total="total">
      </el-pagination>
    </div>


    <!-- 添加或修改问题树对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="45rem" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="9rem">
        <el-form-item label="所属测评量表:" prop="scaleTitle">
          <el-select v-model="form.scaleTitle" @change="handleScaleId" style="width: 17rem;">
            <el-option v-for="(item,index) in scaleTitleList" :label="item.scaleTitle" :value="item.scaleTitle"
              :key="index"></el-option>
          </el-select>
        </el-form-item>

        <!-- 不要，后台增	 -->
        <!-- <el-form-item label="问题序号:" prop="questionOrder">
          <el-input v-model="form.questionOrder" />
        </el-form-item> -->

        <el-form-item label="问题内容:" prop="questionContent">
          <el-input v-model="form.questionContent" style="width: 17rem;"/>
        </el-form-item>

        <el-form-item label="所属因子维度:" prop="factorName" @change="handleFactorId">
          <!-- <el-input v-model="form.factorName" /> -->
          <el-select v-model="form.factorName" style="width: 17rem;">
            <el-option v-for="(item,index) in factorNameList" :label="item.factorName" :value="item.factorName"
              :key="index"></el-option>
          </el-select>
        </el-form-item>


        <el-divider content-position="center">问题选项信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddScaleQuestion">增加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteScaleQuestion">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="scaleAnswerList" :row-class-name="rowScaleQuestionIndex"
          @selection-change="handleScaleQuestionSelectionChange" ref="scaleQuestion" tooltip-effect="dark myTooltips">
          <el-table-column type="selection" align="center" />
          <el-table-column label="序号" align="center" prop="index" />
          <el-table-column label="选项" prop="answerOption" align="center">
            <!-- <el-input v-model="this.form1.answerOption"/> -->
            <template slot-scope="scope">
              <el-input v-model="scope.row.answerOption" />
            </template>
          </el-table-column>
          <el-table-column label="得分" prop="score" align="center">
            <!-- <el-input v-model="this.score" /> -->
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.score" @change="handleChange" label="描述文字"></el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQuestionTree, getQuestionTree, delQuestionTree, addQuestionTree, updateQuestionTree } from "@/api/system/questionTree";
import { listScale, getScale } from "@/api/mentalTest/scaleManage";
import { listFactor, getFactor } from '@/api/system/factor'

export default {
  name: "QuestionTree",
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 临时表表格数据
      questionTreeList: [],
      //所属测评量表标题数据
      scaleTitleList: [],
      //因子维度数据
      factorNameList: [],
      // 问题树信息表格数据
      scaleAnswerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      scaleTitle:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        questionId: null,
        scaleId: null,
        questionOrder: null,
        questionContent: '',
        factorId: null,
        factorName: '',
        scaleTitle: '',
        scaleAnswerList: []
      },
      //查询所属测评量表的参数
      queryTitle: {
        scaleId: null,
        scaleTitle: '',
      },
      //查询因子维度表的参数
      queryFactorName: {
        factorId: null,
        factorName: '',
      },
      // 表单参数
      form: {
        questionId: null,
        scaleId: null,
        questionOrder: null,
        questionContent: '',
        factorId: null,
        factorName: '',
        scaleTitle: '',
        scaleAnswerList: []
      },
      // 表单校验
      rules: {
      },
      routerScaleTitle: ''
    };
  },
  created () {
    this.getTitle();
    this.getFactorName();
    this.getRouterQuery()
  },
  mounted () {
    this.getList();
  },
  methods: {
    //获取路由参数
    getRouterQuery () {
      this.queryParams.scaleTitle = this.$router.history.current.query.scaleTitle;
      this.scaleTitle = this.queryParams.scaleTitle;
    },
    /** 查询临时表 列表 */
    getList () {
      this.loading = true;
      listQuestionTree(this.queryParams).then(response => {
        console.log("222", this.queryParams);
        this.questionTreeList = response.rows;
        this.total = response.total;
        this.loading = false;
        // console.log("问题树",this.questionTreeList);
        console.log("response", response);

      });
    },
    //从questionInfo得到所有所属测评量表的标题
    getTitle () {
      // this.queryParams.scaleTitle = '所有';
      listScale(this.queryTitle).then(response => {
        this.scaleTitleList = response.rows;
      })
    },
    //要从factor中获取所有的因子维度
    getFactorName () {
      // this.queryParams.factorName = '所有';
      listFactor(this.queryFactorName).then(response => {
        this.factorNameList = response.rows;
        // console.log("所有的因子维度",this.factorNameList);
      })
    },
    // 分页器页码改变事件
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange (val) {
      // this.queryParams.pageNum = val
      console.log(`当前页: ${this.queryParams.pageNum}`);
      listQuestionTree({
        pageNum: val,
        pageSize: 10,
        questionId: null,
        scaleId: null,
        questionOrder: null,
        questionContent: '',
        factorId: null,
        factorName: '',
        scaleTitle: ''
      }).then(response => {
        this.questionTreeList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log('res', this.questionTreeList)
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        questionId: null,
        scaleId: null,
        questionOrder: null,
        questionContent: '',
        factorId: null,
        factorName: '',
        scaleTitle: '',
        scaleAnswerList: []
      };
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        questionId: null,
        scaleId: null,
        questionOrder: null,
        questionContent: '',
        factorId: null,
        factorName: '',
        scaleTitle: '',
        scaleAnswerList: []
      }
      this.resetForm("form");
    },
     //添加问题中的得分控件
    handleChange(value) {
        console.log(value);
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      console.log("1111", this.queryParams);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.reset();
      this.handleQuery();
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.questionId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 复选框选中数据 */
    handleScaleQuestionSelectionChange (selection) {
      this.checkedScaleQuestion = selection.map(item => item.index)
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.scaleAnswerList = [];
      this.form.scaleTitle = "请选择";
      this.form.factorName = "请选择"
      this.getTitle();
      this.getFactorName();
      this.open = true;
      this.title = "添加测评量表问题信息";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const questionId = row.questionId || this.ids
      getQuestionTree(questionId).then(response => {
        this.form = response.data;
        this.scaleAnswerList = this.form.scaleAnswerList
        // console.log("修改显示要的内容",this.form);
        this.open = true;
        this.title = "修改测评量表问题信息";
        getScale(this.form.scaleId).then(response1 => {
          this.form.scaleTitle = response1.data.scaleTitle
          // console.log("111",response1.data);
        })
        getFactor(this.form.factorId).then(response2 => {
          this.form.factorName = response2.data.factorName
        })
      });
    },
    /** 问题树信息序号 */
    rowScaleQuestionIndex ({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 问题树信息添加按钮操作 */
    handleAddScaleQuestion () {
      let obj = {};
      obj.answerOption = "";
      obj.score = "";
      this.scaleAnswerList.push(obj);
    },
    /** 问题树信息删除按钮操作 */
    handleDeleteScaleQuestion () {
      if (this.checkedScaleQuestion.length == 0) {
        this.$modal.msgError("请先选择要删除的问题树信息数据");
      } else {
        const scaleAnswerList = this.scaleAnswerList;
        const checkedScaleQuestion = this.checkedScaleQuestion;
        this.scaleAnswerList = scaleAnswerList.filter(function (item) {
          return checkedScaleQuestion.indexOf(item.index) == -1
        });
      }
    },
    //为得到scaleId的回调函数
    handleScaleId (selectedValue) {
      const selectedScale = this.scaleTitleList.find(item => item.scaleTitle === selectedValue);
      if (selectedScale) {
        const scaleId = selectedScale.scaleId;
        this.form.scaleId = scaleId
        this.queryParams.scaleId = scaleId
      }
    },
    //为得到factorId的回调函数
    handleFactorId (selectedValue) {
      const selectedFactor = this.factorNameList.find(item => item.factorName === selectedValue);
      if (selectedFactor) {
        const factorId = selectedFactor.factorId;
        this.form.factorId = factorId;
        this.queryParams.factorId = factorId;
        // console.log('Selected formulaId:', formulaId);
      }
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.questionId != null) {
            // console.log("1111",this.form);
            // console.log("2222",this.scaleAnswerList);
            updateQuestionTree(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              if(this.scaleTitle){
                this.queryParams.scaleTitle = this.scaleTitle;
              }
              this.getList();
            });
          } else {
            // console.log("1111",this.form);
            addQuestionTree(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //问题选项信息
    gotoOption (row) {
      this.$router.push({
        path: '/mentalTest/scaleSet/optionInfo',
        query: {
          questionContent: row.questionContent
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = (row.questionId || this.ids) + '';
      console.log("ids", typeof ids)
      this.$modal.confirm('是否确认删除临时表编号为"' + ids + '"的数据项？').then(function () {
        return delQuestionTree(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('system/questionTree/export', {
        ...this.queryParams
      }, `questionTree_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
